package com.zlq.cn.admin.service;

import com.zlq.cn.admin.domain.vo.AdminVo;
import com.zlq.cn.api.ApiCodeEnum;
import com.zlq.cn.api.ResponseException;
import com.zlq.cn.util.ServletUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.Duration;

/**
 * @author zhoucl
 * @date 2022年12月20日 16:29
 */
@Service
public class AdminTokenService {
    private static final String KEY_TOKEN = "token";

    private static RedisTemplate redisTemplate;

    public AdminTokenService(RedisTemplate redisTemplate) {
        AdminTokenService.redisTemplate = redisTemplate;
    }

    public static void login(AdminVo admin) {
        redisTemplate.opsForValue().set(getTokenKey(admin.getToken()), admin, Duration.ofDays(1));
    }

    public static void logout() {
        AdminVo adminUser = getAdminUser();
        if (adminUser != null) {
            redisTemplate.delete(getTokenKey(adminUser.getToken()));
        }
    }

    public static AdminVo requestUser() {
        AdminVo adminUser = getAdminUser();
        if (adminUser == null) {
            ResponseException.resultError(ApiCodeEnum.TOKEN_INVALID);
        }
        return adminUser;
    }

    public static AdminVo getAdminUser() {
        HttpServletRequest request = ServletUtils.getRequest();
        if (request == null) {
            return null;
        }
        Object attribute = request.getAttribute(KEY_TOKEN);
        if (attribute == null) {
            String requestToken = getRequestToken();
            if (requestToken == null) {
                return null;
            }
            attribute = redisTemplate.opsForValue().get(getTokenKey(requestToken));
            if (attribute != null) {
                request.setAttribute(KEY_TOKEN, attribute);
            }
        }
        return attribute != null ? (AdminVo) attribute : null;
    }

    private static String getRequestToken() {
        HttpServletRequest request = ServletUtils.getRequest();
        if (request == null) {
            return null;
        }
        return request.getHeader("token");
    }

    private static String getTokenKey(String token) {
        return KEY_TOKEN + ":" + token;
    }
}
